/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * scheduleDayPanel.java
 *
 * Created on 10 Ιουν 2010, 6:54:42 πμ
 */
package myseriesproject.schedule;

import com.googlecode.scheduler.ScheduleDay;
import database.DBHelper;
import database.EpisodesRecord;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import myseriesproject.MySeries;
import myseriesproject.MySeriesConstants;
import tools.MySeriesLogger;
import tools.options.MySeriesOptions;
import tools.options.Paths;

/**
 *
 * @author ssoldatos
 */
public class ScheduleDayPanel extends javax.swing.JPanel {

  private static final long serialVersionUID = 234534643563L;
  private final Object value;
  private final JLabel dayLabel;
  private final int height;
  private final int width;
  private ScheduleDay sDay;
  private ArrayList<ScheduleEvent> events;
  private int rows;
  private int MAX_COLUMNS = 2;
  private int GAP = 2;
  private int MIN_COLUMNS = 1;
  private int NUMBER_LABEL_WIDTH = 30;

  public ScheduleDayPanel(Object value, JLabel dayLabel, int height, int width) {
    this.value = value;
    this.dayLabel = dayLabel;
    this.height = height;
    this.width = width;
    initComponents();
    if (!(this.value instanceof ScheduleDay)) {
      createDefaultPanel();
    } else {
      sDay = (ScheduleDay) value;
      events = DBHelper.getDayEvents(sDay);
      createDefaultPanel();
      if (events.isEmpty()) {
      } else {
        createPanel();
      }
    }
    validate();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    number = new javax.swing.JPanel();
    icons = new javax.swing.JPanel();

    setBackground(MySeries.options.getColorOption(MySeriesOptions.SKIN_COLOR));
    setMaximumSize(new Dimension(width, height));
    setMinimumSize(new Dimension(width, height));
    setPreferredSize(new Dimension(width, height));
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.LINE_AXIS));

    number.setMaximumSize(new Dimension(NUMBER_LABEL_WIDTH, height));
    number.setMinimumSize(new Dimension(NUMBER_LABEL_WIDTH, 0));
    number.setOpaque(false);
    number.setPreferredSize(new Dimension(NUMBER_LABEL_WIDTH, height));
    number.setLayout(new java.awt.GridLayout(1, 0));
    add(number);

    icons.setOpaque(false);
    icons.setLayout(null);
    add(icons);
  }// </editor-fold>//GEN-END:initComponents
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JPanel icons;
  private javax.swing.JPanel number;
  // End of variables declaration//GEN-END:variables

  private void createDefaultPanel() {
    number.add(dayLabel);
    number.setToolTipText("");
    setBackground(dayLabel.getBackground());

  }

  private void createPanel() {
    ImageIcon orIm;
    MySeriesLogger.logger.log(Level.INFO, "Creating day panel");
    rows = (int) Math.ceil((double) events.size() / MAX_COLUMNS);
    icons.setLayout(new GridLayout(rows, events.size() == 1 ? MIN_COLUMNS : MAX_COLUMNS, GAP, GAP));
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    String date = sdf.format(sDay.getDate());
    String tip = "<html><table>";
    tip += "<tr><td><b>" + date + "</b></td></tr>";
    for (Iterator<ScheduleEvent> it = events.iterator(); it.hasNext();) {
      ScheduleEvent event = it.next();
      MySeriesLogger.logger.log(Level.INFO, "Creating event {0}",event.toString());
      JLabel eventLabel = new JLabel();
      tip += "<tr><th>" + event.getSeries() + "</th></tr>";
      tip += "<tr><td>" + event.getEpisodeNumber() + "." + event.getEpisode() + "</td></tr>";
      tip += "<tr><td><hr></td></tr>";
      if (event.getImage().equals("")) {
        MySeriesLogger.logger.log(Level.INFO, "Setting default screenshot for {0}",event.getSeries());
        orIm = getScaledImageIcon(getDefaultImage().getImage());
      } else {
        File sc = new File(MySeriesOptions._USER_DIR_ + Paths.SCREENSHOTS_PATH + event.getImage());
        if(sc.exists()){
        MySeriesLogger.logger.log(Level.INFO, "Setting series screenshot for {0}",event.getSeries());
        orIm = getScaledImageIcon(new ImageIcon(sc.getAbsolutePath()).getImage());
        } else {
          MySeriesLogger.logger.log(Level.INFO, "Setting default screenshot for {0}",event.getSeries());
          orIm = getScaledImageIcon(getDefaultImage().getImage());
        }
      }
      orIm = addDownloadStatus(orIm, event.getDownloaded(),event.getSeen());
      eventLabel.setMaximumSize(new Dimension(orIm.getIconWidth(), orIm.getIconHeight()));
      eventLabel.setIcon(orIm);
      eventLabel.setHorizontalAlignment(SwingConstants.CENTER);
      icons.add(eventLabel);
      MySeriesLogger.logger.log(Level.FINE, "Event added");
    }
    tip += "</table></html>";
    setToolTipText(tip);
  }

  private ImageIcon getScaledImageIcon(Image image) {
    ImageIcon im = null;
    MySeriesLogger.logger.log(Level.INFO, "Scaling image");
    try {
      double w = image.getWidth(this);
      double h = image.getHeight(this);
      double ratio = w / h;
      if (w > (width - NUMBER_LABEL_WIDTH)) {
        w = width - NUMBER_LABEL_WIDTH;
        h = w / ratio;
      }
      if (h > height) {
        h = height;
        w =h * ratio;
      }


      double newW = 0, newH = 0;
      if (events.size() == 1) {
        if (w >= h) {
          newW = width - NUMBER_LABEL_WIDTH;
          newH =h / (w / newW);
        } else {
          newH = height;
          newW = w / (h / newH);
        }
      } else {
        newW = ((width - NUMBER_LABEL_WIDTH) / MAX_COLUMNS) - (rows * GAP);
        newH =h / (w / newW);
      }
      im = new ImageIcon(image.getScaledInstance((int)newW,(int) newH, MySeriesOptions.IMAGE_SCALING[MySeries.options.getIntegerOption(MySeriesOptions.IMAGE_QUALITY)]));
      MySeriesLogger.logger.log(Level.FINE, "Image scaled");
    } catch (Exception ex) {
      MySeriesLogger.logger.log(Level.INFO, "Could not scale image.Using default image");
      return getScaledImageIcon(getDefaultImage().getImage());
    }
    return im;
  }

  public ImageIcon getDefaultImage() {
    ImageIcon im = new ImageIcon(getClass().getResource(MySeriesConstants.LOGO));
    return im;
  }

  private ImageIcon addDownloadStatus(ImageIcon orIm, int downloaded, int seen) {
    MySeriesLogger.logger.log(Level.INFO, "Adding download status");
    int imWidth = orIm.getIconWidth();
    int imHeight = orIm.getIconHeight();
    ImageIcon indicator = null;
    if (downloaded == EpisodesRecord.DOWNLOADED || seen == EpisodesRecord.SEEN) {
      MySeriesLogger.logger.log(Level.INFO, "Is downloaded");
      indicator = getScaledImageIcon("/images/tick_big.png", imWidth, imHeight);
    } else {
      // indicator = getScaledImageIcon("/images/torrent.png", imWidth, imHeight);
    }
    if (indicator != null) {
      BufferedImage buff = new BufferedImage(imWidth, imHeight, BufferedImage.TYPE_INT_ARGB);
      buff.getGraphics().drawImage(orIm.getImage(), 0, 0, this);
      buff.getGraphics().drawImage(indicator.getImage(), imWidth - indicator.getIconWidth(), imHeight - indicator.getIconHeight(), this);
      orIm = new ImageIcon(buff);
      MySeriesLogger.logger.log(Level.FINE, "Added downloaded indicator");
    }
    return orIm;
  }

  private ImageIcon getScaledImageIcon(String imagePath, int imWidth, int imHeight) {
    MySeriesLogger.logger.log(Level.INFO, "Getting scaled image icon for {0}",imagePath);
    ImageIcon im = new ImageIcon(getClass().getResource(imagePath));
    int icWidth = imWidth / 3;
    int icHeight = imWidth / 3;
    if(icHeight==0 || icWidth==0){
      
    }
    Image scaled = im.getImage().getScaledInstance(icWidth, icHeight, MySeriesOptions.IMAGE_SCALING[MySeries.options.getIntegerOption(MySeriesOptions.IMAGE_QUALITY)]);
    MySeriesLogger.logger.log(Level.FINE, "Image scaled");
    return new ImageIcon(scaled);
  }
}
